package z.z.mvc5.controller;

import com.alibaba.fastjson2.JSON;
import org.springframework.core.MethodParameter;
import org.springframework.core.io.Resource;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;
import z.z.mvc5.utils.ApiResponse;

import java.io.InputStream;


/**
 * 全局的相应处理器
 */
@RestControllerAdvice
public class GlobalResponseHandler implements ResponseBodyAdvice<Object> {
    @Override
    public boolean supports(MethodParameter returnType, Class<? extends HttpMessageConverter<?>> converterType) {
        // 通常直接返回 true 表示对所有返回值生效，
        // 也可以在这里使用 returnType 判断是否过滤某些 Controller 或类型
        // 屏蔽所有资源，字节流等类型
        Class<?> parameterType = returnType.getParameterType();
        if (InputStream.class.isAssignableFrom(parameterType)) {
            return Boolean.FALSE;
        }
        if (Resource.class.isAssignableFrom(parameterType)) {
            return Boolean.FALSE;
        }
        if (byte[].class.isAssignableFrom(parameterType)) {
            return Boolean.FALSE;
        }
        return Boolean.TRUE;
    }


    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class<? extends HttpMessageConverter<?>> selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        if (body instanceof ApiResponse) {
            return body;
        }
        if (body instanceof String result) {
            return ApiResponse.success(JSON.toJSONString(result));
        }
        return ApiResponse.success(body);
    }
}
